<template>
  <div class="dashboard-container ">
    <div class="dashboard-text">
      <ul>
        <li class="item" :id="item.serial" v-for="item, index in list" :key="index" @click="handleDetail(item)">
          <div class="title">{{ item.title }}</div>
          <div style="color: #ccc; font-size: 12px;">发布时间：{{ item.publishTime }}</div>
          <div class="content" v-if="item.content.length > 0">{{ item.content[0].trim() }}</div>
          <div class="imgs" v-if="item.images.length > 0">
            <img v-for="img, index in item.images" :src="ImgBaseUrl + img" :key="index" class="img" />
          </div>
        </li>
      </ul>

      <span class="djs">您已阅读<br/>{{ min_time }}</span>

      <el-button size="mini" type="danger" class="finish" @click="handleFinish">完成</el-button>
      <el-button size="mini" type="primary" class="clear" @click="handleRefresh">刷新</el-button>

      <!-- 问答弹窗 -->
      <el-dialog title="问卷" :visible.sync="DialogVisible" width="400px" style="max-width: 100%;" center>
        <!-- <span>需要注意的是内容是默认不居中的</span> -->
        <div style="color: black; font-size: 16px; margin-bottom: 10px; font-weight: bold;">请在以下标题中选出已阅读过的5个文章标题</div>
        <div v-for="item, index in questions" :key="index" >
            <el-checkbox-group v-model="checked" style=" display: flex;flex-wrap: wrap;">
              <el-checkbox :label="item.serial" style="margin-bottom: 5px;" >{{ item.title }}</el-checkbox>
            </el-checkbox-group>
        </div>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="DialogVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="handleSubmit">提交问卷</el-button>
        </span>
      </el-dialog>



    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { newsList, newsRead, articleCheckQuestion, articleCheckAnswer, articleBrowseRange} from '@/api/news'
import { ImgBaseUrl } from '@/utils/index'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data() {
    return {
      ImgBaseUrl,
      list: [],
      loading: false, //默认没有加载
      time: 0,
      min_time: '', //显示的分钟数
      DialogVisible: false,
      questions: [],
      checked: [],
      articleList: []
    }
  },
  activated(){
    // 如果时间为0，重新开始定时任务
    if(sessionStorage.getItem('time')==0){
      //如果定时任务不存在，那么久之行定时任务
      window.timer = setInterval(() => {
        let now = this.time + 1;
        this.time = now;
        this.min_time = Math.floor(now/60) + '分钟';
        localStorage.setItem('time', now);
        if(now==600){
          // 如果阅读时间到了10分钟，执行弹窗
        }
      }, 1000)
    }
  },
  mounted() {
    let currentDate = new Date();
    let day = currentDate.getDate();
    let historyDay = localStorage.getItem('day');
    if(historyDay!=day){
      // 重新记录时间，并重置时间为0
      localStorage.setItem('day', day)
      localStorage.setItem('time', 0)
    }
    this.time = Number(localStorage.getItem('time'));
    window.status = 'start'
    window.timer = setInterval(() => {
      
      let now = this.time + 1;
      this.time = now;
      this.min_time = Math.floor(now/60) + '分钟';
      localStorage.setItem('time', now);
      console.log('定时任务在执行', now)
      if(now==600){
        // 如果阅读时间到了10分钟，执行弹窗
      }
    }, 1000)

    window.addEventListener('scroll', this.handleScroll)
    this.getList();

    //获取可见的元素
    let io = new IntersectionObserver(async (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            // 如果可见就上报
            this.articleList.push(entry.target.id)
          } else {
            // 元素不可见，移除样式
            this.articleList = this.articleList.filter(item=>item!=entry.target.id)
          }
        });
        

    });

    // 开始观察
    let readTimer = setInterval(async ()=>{
      const targets = document.querySelectorAll('.item');
        targets.forEach(target => {
            io.observe(target);
        });
        console.log()
        // 过滤掉为空的情况
        if(this.articleList.length>0&&window.location.href.indexOf('detail')==-1){
          await articleBrowseRange({ articleList: this.articleList })
        }
        
    }, 1000)

  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  activated(){
    if(window.status=='end'){
      this.time = Number(localStorage.getItem('time'));
      window.status = 'start'
      window.timer = setInterval(() => {
        let now = this.time + 1;
        this.time = now;
        this.min_time = Math.floor(now/60) + '分钟';
        localStorage.setItem('time', now);
        if(now==600){
          // 如果阅读时间到了10分钟，执行弹窗
        }
      }, 1000)
    }
  },
  methods: {
    // 点击完成
    handleFinish() {
      if (this.time < 10) { //改为600
        this.$message.error({
          message: '请阅读满10分钟后提交,已经阅读' + this.time + '秒'
        })
        return;
      }
      window.status = 'end'
      clearInterval(window.timer);
      sessionStorage.setItem('type', 'end')
      this.$router.push('/start')
    },
    // 滚动事件
    handleScroll() {
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      if ((scrollTop + windowHeight) > (scrollHeight - 40) && !this.loading) {
        //到达底部
        this.loading = true;
        this.getList();
      }
    },
    //点击跳转详情
    async handleDetail(item) {
      await newsRead({ serial: item.serial })
      if (sessionStorage.getItem('readNumber')) {
        let readNumber = Number(sessionStorage.getItem('readNumber')) + 1;
        sessionStorage.setItem('readNumber', readNumber)
      } else {
        sessionStorage.setItem('readNumber', 1)
      }
      sessionStorage.setItem('title', item.title);
      sessionStorage.setItem('content', JSON.stringify(item.content));
      sessionStorage.setItem('images', JSON.stringify(item.images));
      sessionStorage.setItem('serial', item.serial);
      this.$router.push('./detail')
    },
    handleRefresh() {
      this.list = [];
      //返回页面顶部
      window.scrollTo(0, 0);
      this.getList();
    },
    async getList() {
      let list = await newsList();
      list.data = list.data.map(item=>{
        let date = new Date(item.publishTime);
        item.publishTime = date.getFullYear() + '年' + (date.getMonth()+1) + '月' + date.getDate()+'日'; 
        return item;
      })
      this.list = this.list.concat(list.data);
      this.loading = false;
    },
    //查询问卷内容
    async getQuestion() {
      let { data } = await articleCheckQuestion({})
      this.questions = data;
      this.DialogVisible = true;
    },
    //提交问卷
    async handleSubmit() {
      if(this.checked.length==5){
        this.DialogVisible = false;
        await articleCheckAnswer({articleList: this.checked})
        this.$message.success({ message: '提交成功' })
        
        sessionStorage.removeItem('finish')
        
      }else{
        this.$message.error({ message: '请选择5个标题' })
      }
      
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    ::v-deep .el-checkbox__label {
			vertical-align: text-top;
			white-space: normal;
			word-break: break-all;
		}
    .djs {
      position: fixed;
      top: 10px;
      left: 5px;
      color: #409EFF;
    }

    font-size: 16px;
    line-height: 20px;
    max-width: 800px;
    margin: 0 auto;

    ul {
      padding: 0 0 10px;
      margin: 0 auto 10px;
    }

    .item {
      list-style: none;
      box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 15px;
      padding: 10px;
      border-radius: 5px;

      .title {
        font-weight: bold;
        font-size: 20px;
        margin-bottom: 10px;
        font-weight: 20px;
      }

      .content {
        color: #333;
        text-indent: 0;
      }

      .imgs {
        // width: 100%;
        padding-top: 10px;
        overflow-y: auto;
        white-space: nowrap;
        height: 120px;

        .img {
          width: 150px;
          height: 100px;
          margin-right: 10px;
        }
      }
    }

    .clear {
      position: fixed;
      bottom: 10%;
      right: 5%;
    }

    .finish {
      position: fixed;
      bottom: 14%;
      right: 5%;
      font-weight: bold;
    }
  }
}
</style>
